package com.aprivate.leo.libarouter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import dalvik.system.DexFile;

/**
 * Author: Administrator
 * Date: 2020/2/10
 * Project: ModularizationTemplateApp
 * Description:
 */
public class Router {
    private static Router INSTANCE;
    private Map<String, Class<? extends Activity>>  mMap = new HashMap<>();
    private Context mContext;

    private Router() {

    }

    public static Router getInstance() {
        if (INSTANCE == null) {
            synchronized (Router.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Router();
                }
            }
        }
        return INSTANCE;
    }

    public void init(Context context) {
        mContext = context;
        List<String> claNames = getAllClassWithPackageName("com.aprivate.leo.activityutils");
        addActivities(claNames);
    }

    private void addActivities(List<String> claNames) {
        for(String name:claNames){
            try {
                Class<?> aClass = Class.forName(name);
                if(IRouter.class.isAssignableFrom(aClass)){
                    IRouter instance = (IRouter) aClass.newInstance();
                    instance.putActivities();
                }

            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                e.printStackTrace();
            }
        }
    }

    private List<String> getAllClassWithPackageName(String pkgName) {
        List<String> list = new ArrayList<>();
        try {
            String sourceDir = mContext.getPackageManager().getApplicationInfo(mContext.getPackageName(), 0).sourceDir;
            DexFile dexFile = new DexFile(sourceDir);
            Enumeration<String> entries = dexFile.entries();
            while (entries.hasMoreElements()){
                String element = entries.nextElement();
                if(element.contains(pkgName)){
                    list.add(element);
                }
            }
        } catch (PackageManager.NameNotFoundException | IOException e) {
            e.printStackTrace();
        }
        return list;
    }


    public void putActivity(String key, Class<? extends Activity> cls) {
        mMap.put(key, cls);
    }

    public void jumpToActivity(String key, @Nullable Bundle bundle) {
        Class<? extends Activity> aClass = mMap.get(key);
        if (aClass != null) {
            Intent intent = new Intent();
            intent.setClass(mContext, aClass);
            if (bundle != null) {
                intent.putExtras(bundle);
            }
            mContext.startActivity(intent);
        }
    }


}
